Ext.onReady(function() {
	Ext.define('GroupModel', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'QUERYGRPID', type:'string'},
            {name: 'GRPID', type:'string'},
            {name: 'GROUPNAME', type:'string'},
            {name: 'REMARK', type:'string'},
            {name: 'MAKEDATE', type:'DATE'},
            {name: 'OPERATOR', type:'string'},
        ]
    });
	
	var groupStore = Ext.create('Ext.data.Store',{
		model: GroupModel
	});
	
	var queryGroupId = Ext.create('Ext.form.field.Text',{
        fieldLabel: str_grpmgr_usergroup,
        labelWidth: 60
	});
	
	var groupGrid = Ext.create('Ext.grid.Panel', {
		border: false,
		title: str_grpmgr_ugquery,
		loadMask : true,
		store:groupStore,
		region:'center',
		autoScroll: true,
		columns: [
          {
              xtype: 'rownumberer',
              width: 30,
              hideable: false
          },
          {
        	  xtype: 'gridcolumn',
        	  text: str_grpmgr_ugname,
              width: 100,
              defaultWidth: 0,
              dataIndex: 'GROUPNAME',
              hideable: false
          },
          {
        	  xtype: 'gridcolumn',
        	  text: str_grpmgr_ugid,
              width: 100,
              defaultWidth: 0,
              dataIndex: 'GRPID',
              hideable: false
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'REMARK',
              text: str_grpmgr_discrip,
              flex: 1
          },
          {
              xtype: 'datecolumn',
              dataIndex: 'MAKEDATE',
              format: 'Y-m-d',
              width: 80,
              text: str_grpmgr_credate
          },
          {
              xtype: 'gridcolumn',
              width: 80,
              dataIndex: 'OPERATOR',
              text: str_grpmgr_creperson
          }
        ],
	    dockedItems: [
		  {
		      xtype: 'toolbar',
		      dock: 'top',
		      items: [
                  queryGroupId,
                  {
                	  xtype: 'button',
                	  text: str_common_query,
                	  listeners: {
                          click: {
                        	  fn:queryGroup
                          }
                      }
                  }
		      ]
		   },
		   {
	              xtype: 'pagingtoolbar',
	              displayInfo: true,
	              store: groupStore,
	              dock: 'bottom'
	       }
		],
		listeners: {
            selectionchange: function(model, records) {
                if (records[0]) {
                	groupForm.loadRecord(records[0]);
                    loadMenuTree(formGroupQueryid.value);
                }
            }
        }
    });
	
	function queryGroup(){
		groupStore.setProxy({
			type : 'ajax',
			actionMethods: 'POST',
			url : getPath("/aa/po/groupManager.do"),
			extraParams : {
            	"md":"queryGroup",
            	"GROUPID":queryGroupId.getRawValue()
            },
			reader : {
				type : 'json',
				root : 'group',
				totalProperty : 'totalCount'
			}
		});
		groupStore.load();
	}
	
    
    var formGroupQueryid = Ext.create('Ext.form.field.Hidden',{
        name: 'QUERYGRPID'
    });
    
    var formGroupid = Ext.create('Ext.form.field.Text',{
    	name: 'GRPID',
    	fieldLabel: str_grpmgr_ugid,
    	width: 285,
        labelWidth: 80
    });
    
    var formGroupName = Ext.create('Ext.form.field.Text',{
    	fieldLabel: str_grpmgr_ugname,
    	name: 'GROUPNAME',
    	width: 285,
        labelWidth: 80
    });
    
    var formRemark = Ext.create('Ext.form.field.Text',{
    	fieldLabel: str_grpmgr_discrip,
    	name: 'REMARK',
    	width: 285,
        labelWidth: 80
    });
	
	var groupMenuStore = Ext.create('Ext.data.TreeStore', {
		sorters: [{
	        property: 'order',
	        direction: 'ASC'
	    }]
    });
	
	var treeIsLoaded = false;
	
	function loadMenuTree(groupid){
		groupMenuStore.setProxy({
			type : 'ajax',
			url : getPath("/ab/po/houseKeeper.do"),
			type : 'ajax',
			url : ctx+'/aa/po/index.do',
			loadMask : true,
			extraParams : {
            	"md":"menu",
            	"GROUPID": groupid
            }
		});
		groupMenuStore.load();
		treeIsLoaded = true;
	}
	
    var groupMenuTree = Ext.create('Ext.tree.Panel', {
        store: groupMenuStore,
        rootVisible: false,
        useArrows: true,
        margin:'0 20 10 0',
        region:'center',
        minHeight:330,
        width:200,
        autoScroll: true
    });
	
	var groupForm = Ext.create('Ext.form.Panel', {
        layout: 'border',
        border: false,
        region:'east',
        width: 330,
        items: [{
        	xtype: 'fieldset',
            title:str_grpmgr_ugedit,
            margin : '0 10 0 10',
            defaultType: 'textfield',
            items: [formGroupQueryid,formGroupid,formGroupName,formRemark,{
            	xtype: 'container',
                layout: {
                    type: 'hbox'
                },
                width: 300,
                items: [{
                    xtype: 'label',
                    text: str_grpmgr_ownmenu,
                    width: 85
                    },
                    groupMenuTree
                ]
            }]
        }],
        buttons:[{
            text: str_common_new,
            handler:createNewGroup
        },{
            text: str_common_change,
            handler:updateGroup
        },{
            text: str_common_delete,
            handler:deleteGroup
        }]
    });
	
	function getMenuTreeSelected(){
        var records = groupMenuTree.getView().getChecked();
        var names = "";
        Ext.Array.each(records, function(rec){
            names += rec.get('id');
            names += ",";
        });
        return names;
	}
	
	function createNewGroup(){
		var groupId = formGroupid.getRawValue();
		var groupName = formGroupName.getRawValue();
		var groupRemark = formRemark.getRawValue();
		var selectedMenu = getMenuTreeSelected();
		if (isBlank(groupId)) {
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_ugidnull);
			return false;
		}
		if(isBlank(groupName)){
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_ugnamenull);
			return false;
		}
		if(selectedMenu.length == 0){
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_plsselmenu);
			return false;
		}
		Ext.Ajax.request({
            url : getPath("/aa/po/groupManager.do"),  
            params : {
            	"md":"addgroup",
                "GRPID" : groupId,
                "GROUPNAME" : groupName,
                "REMARK" : groupRemark,
                "MENUS": selectedMenu
            },
            success : function(response) {  
            	var ret = Ext.JSON.decode(response.responseText);
            	if(!ret.success){
            		Ext.MessageBox.alert(str_common_error,ret.msg);
            	}
            	else{
            		Ext.MessageBox.alert(str_common_success,ret.msg);
            	}
            }
        });
	}
	
	function deleteGroup(){
		var groupQueryId = formGroupQueryid.getRawValue();
		var groupId = formGroupid.getRawValue();
		if(isBlank(groupQueryId) || groupQueryId != groupId) {
			Ext.MessageBox.alert(str_common_warn, str_grpmgr_plsqueryseldel);
			return false;
		}
		Ext.Ajax.request({
            url : getPath("/aa/po/groupManager.do"),  
            params : {
            	"md":"deletegroup",
                "GRPID" : groupQueryId
            },
            success : function(response) {  
            	var ret = Ext.JSON.decode(response.responseText);
            	if(!ret.success){
            		Ext.MessageBox.alert(str_common_error,ret.msg);
            	}
            	else{
            		Ext.MessageBox.alert(str_common_success,ret.msg);
            		reset();
            	}
            }
        });
	}
	
	function updateGroup(){
		var groupQueryId = formGroupQueryid.getRawValue();
		var groupId = formGroupid.getRawValue();
		var groupName = formGroupName.getRawValue();
		var groupRemark = formRemark.getRawValue();
		var selectedMenu = getMenuTreeSelected();
		if (isBlank(groupQueryId)) {
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_plsqueryselchg);
			return false;
		}
		if (groupQueryId != groupId) {
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_ugidchg);
			return false;
		}
		if(isBlank(groupName)){
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_ugnamenull);
			return false;
		}
		if(selectedMenu.length == 0){
			Ext.MessageBox.alert(str_common_warn,str_grpmgr_plsselmenu);
			return false;
		}
		Ext.Ajax.request({
            url : getPath("/aa/po/groupManager.do"),  
            params : {
            	"md":"updategroup",
                "GRPID" : groupId,
                "GROUPNAME" : groupName,
                "REMARK" : groupRemark,
                "MENUS": selectedMenu
            },
            success : function(response) {  
            	var ret = Ext.JSON.decode(response.responseText);
            	if(!ret.success){
            		Ext.MessageBox.alert(str_common_error,ret.msg);
            	}
            	else{
            		Ext.MessageBox.alert(str_common_success,ret.msg);
            		reset();
            	}
            }
        });
	}
	
	function reset(){
		formGroupQueryid.reset();
		formGroupid.reset();
		formGroupName.reset();
		formRemark.reset();
		loadMenuTree("Base");
		queryGroup();
	}
	
	userGroupWin = Ext.create('Ext.Window', {
		maximizable: true,
        title: str_grpmgr_ugmanager,
        height: 520,
        width: 840,
        iconCls: 'icon-group',
        layout: {
            type: 'fit'
        },
        closeAction: 'hide',
        items: [{
        	xtype: 'container',
            layout: 'border',
        	items:[groupGrid,groupForm]
        }],
        x: 100,
        y: 60,
        listeners:{
        	hide:function(){
        		if(userGroupMgrBtn.pressed){
        			userGroupMgrBtn.toggle();
        		}
        	},
        	beforeshow:function(){
        		if(!treeIsLoaded) {
        			loadMenuTree("Base");
        		}
        	}
        }
    });
});